<template>
  <h1>登录</h1>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" style="width: 100%">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="账号"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        type="password"
        placeholder="密码"
        show-password
        autocomplete="new-password"
      ></el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button type="primary" :loading="loading" @click="login(loginFormRef)"> 登录 </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onBeforeUnmount, onMounted } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { ElForm, ElMessage } from "element-plus";
import { useTokenStore } from "@/stores/token.js";
import { userLoginService } from "@/api/systemManage/user.js";
const router = useRouter();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const tokenStore = useTokenStore();
const userStore = useUserStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = ref({
  username: "",
  password: ""
});

//login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      let result = await userLoginService(loginForm.value);
      if (result.data.code === 1) {
        ElMessage.error("登陆失败：" + result.data.message);
        return;
      }
      tokenStore.setToken(result.data.data.saTokenInfo);
      userStore.setUserInfo({ name: loginForm.value.username, userId: result.data.data.userId, role: result.data.data.role });
      // 2.添加动态路由
      await initDynamicRouter();
      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);
      // 4.跳转到首页
      router.replace(HOME_URL);
    } finally {
      loading.value = false;
    }
  });
};

onBeforeUnmount(() => {
  document.onkeydown = null;
});

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";
h1 {
  animation: enter-x-animation 0.4s ease-in-out 0.3s;
  animation-fill-mode: forwards;
  animation-delay: 0.1s;
}
.el-input {
  min-width: 360px;
  height: 50px;
  padding: 7px 11px;
  font-size: 16px;
  line-height: 1.5;
  border-radius: 8px;
  animation: enter-x-animation 0.4s ease-in-out 0.3s;
  animation-fill-mode: forwards;
  animation-delay: 0.2s;
}
.login-btn {
  display: flex;
  justify-content: center;
  width: 100%;
  margin-top: 20px;
  white-space: nowrap;
  .el-button {
    font-size: 16px;
    height: 40px;
    width: 96%;
    padding: 6.428571428571429px 15px;
    border-radius: 8px;
    color: #fff;
    background-color: #0960bd;
    animation: enter-x-animation 0.4s ease-in-out 0.3s;
    animation-fill-mode: forwards;
    animation-delay: 0.3s;
  }
}
@keyframes enter-x-animation {
  from {
    transform: translateX(100px); /* 初始状态，图片从左侧进入 */
    opacity: 0; /* 动画从透明开始 */
  }
  to {
    transform: translateX(0); /* 结束状态，图片回到正常位置 */
    opacity: 1; /* 结束时完全不透明 */
  }
}
</style>
